package metu.tespit.session.sessionScopeManager;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import metu.tespit.entitiy.accountManagement.User;
import metu.tespit.entity.semester.Semester;
import metu.tespit.session.semester.SemesterList;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.security.Identity;

/**
 
 * @created May 20, 2012
 */
@Scope(ScopeType.SESSION)
@Name("sessionScopeBean")
public class SessionScopeBean {

	private Semester activeSemester;
	private User user;

	@In(required=false) Identity identity;
	@In EntityManager entityManager;

	public void setActiveSemester(Semester activeSemester) {
		this.activeSemester = activeSemester;
	}

	public Semester getActiveSemester() {
		
		if(activeSemester==null){
			SemesterList sl = new SemesterList();
			sl.setCurrentDate(new Date());
			List<Semester> sm= sl.getResultList();
			if(sm.size()>0){
				this.setActiveSemester(sm.get(0));
			}
			
		}
		return activeSemester;
	}

	public User getUser() {
		if(user == null && identity != null){
			user = this.findByUserName(identity.getUsername());
		}
		return user;
	}
	
	public User findByUserName(String username){
		return (User) entityManager.createQuery("from User u where u.username = :username").setParameter("username", username).getSingleResult();
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	
}
